<?php

namespace App\Http\Controllers;

use App\Models\Goods;
use App\Models\Order;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;

class NotifyController extends Controller
{

    protected function options(){ //选项设置
        return [
            // 前面的appid什么的也得保留哦
            'app_id' => 'wxd731c1ecac85957c', //你的APPID
            'secret'  => '91fb964d6cc2220edd4e7bdf8121182c',     // AppSecret
            // 'token'   => 'your-token',          // Token
            // 'aes_key' => '',                    // EncodingAESKey，安全模式下请一定要填写！！！
            // ...
            // payment
            'payment' => [
                'merchant_id'        => '1480736172',
                'key'                => '5a73c9e7f81d5778ebcc7f9e2c89096c',
                // 'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
                // 'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
                'notify_url'         => 'http://egui.gebixianxiang.com/wechat/notify',       // 你也可以在下单时单独设置来想覆盖它
                // 'device_info'     => '013467007045764',
                // 'sub_app_id'      => '',
                // 'sub_merchant_id' => '',
                // ...
            ],
        ];
    }

    public function alipay_notify(Request $request)
    {
        file_put_contents('log.txt',var_export($request->all(),true)) ;
        $input = $request->all();
        if($input['trade_status']=="TRADE_SUCCESS"){
            if($input['extra_common_param']=='a_pay_for_goods'){
                Order::where('order_sn',$input['out_trade_no'])->update(['status'=>2]);
            }
        }
        return 'success';
    }

    public function order_detail(Request $request)
    {
        if($order = Order::where('order_sn',$request->get('order_sn'))
            ->first([
                'order_sn','sum_price','freight','created_at',
            ])){
            $order->pay_type=$request->get('pay_type');
            $order->save();
            $order->total = $order->sum_price+$order->freight;
            $order->passback_param = 'a_pay_for_goods';
            return ['status_code'=>1,'data'=>$order];
        }else{
            return ['status_code'=>0,'message'=>"没有这个订单"];
        }
    }
    
    
    public function wechat_notify(Request $request)
    {

        $options = $this->options();
        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){

            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            if (!$order = Order::where('order_sn',$notify['out_trade_no'])->first()) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($order->pay_time) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $order->pay_time = date('Y-m-d H:i:s',time()); // 更新支付时间为当前时间
                $order->order_status = 3; //支付成功,
                $order->trade_no = $notify['transaction_id'];
                foreach ($order->my_info as $value){
                    Goods::where('goods_id',$value->goods_id)->increment('sell');
                }
            }
            $order->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }
    

    public function alipay_create(Request $request)
    {

        $total=1;
        // 对签名字符串转义
        function createLinkstring($para) {
            $arg  = "";
            while (list ($key, $val) = each ($para)) {
                $arg.=$key.'="'.$val.'"&';
            }
            //去掉最后一个&字符
            $arg = substr($arg,0,count($arg)-2);
            //如果存在转义字符，那么去掉转义
            if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
            return $arg;
        }
        // 签名生成订单信息
        function rsaSign($data) {
            $priKey =<<<key
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAqj+GtdCdpcwo+PQkXkT4d5XaNBfypByWyYAPhLMCTKInRV7GP6gnipJnDgFOwfgtQrsOec5fwyttHGM3av4EuK7HfQPqBqV52UDGcAUs7hjRWxSP5WvKglR+CAqpqvxxhpxFmS5fXCcqmaBdshZk6ZMvC+cANspXQ2kgwHKKdsvcEdetuT09RxySw40yCGYUzBxD8oBIyMxTAq+XjTlhaA47tmedvjHuRn7leTXxty+6p8jNVsutb4N1Cz/ttOvfrl+1fLLad9quFA/PBoYwUpuTNhOy65+B6HtLIyLMdfJ8eKCx1T2E3Vf8vAPaRx8vKq9o5DFJQj7qH6uMWv271wIDAQABAoIBAQCPhR47B7Leok2oEajXD62mol1grQ+P6cnz9FEgvQejMs+IW20lHMy4tNLLq66JNn5xUt/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hbW0JwmoiNYu2ouI01nqs0cR2hzcKfaOBPr9/B6OCKv3lSXi1ZVI2YoLYkc3fwD4Ficyktqa1x6w=
-----END RSA PRIVATE KEY-----
key;
            $res = openssl_get_privatekey($priKey);
            openssl_sign($data, $sign, $res);
            openssl_free_key($res);
            $sign = base64_encode($sign);
            $sign = urlencode($sign);
            return $sign;
        }
        // 支付宝合作者身份ID，以2088开头的16位纯数字
        $partner = "2088521596797214";
        // 支付宝账号
        $seller_id = '1255692835@qq.com';
        // 异步通知地址
        $notify_url = urlencode('http://ezs.timespost.top/notify');
        // 订单标题
        $subject = 'test';
        // 订单详情
        $body = 'test';
        // 订单号，示例代码使用时间值作为唯一的订单ID号
        $out_trade_no = date('YmdHis', time());

        $parameter = array(
            'service'        => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
            'partner'        => $partner,                   // 必填，合作商户号
            '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
            'out_trade_no'   => $out_trade_no,              // 必填，商户网站唯一订单号
            'subject'        => $subject,                   // 必填，商品名称
            'payment_type'   => '1',                        // 必填，支付类型
            'seller_id'      => $seller_id,                 // 必填，卖家支付宝账号
            'total_fee'      => $total,                     // 必填，总金额，取值范围为[0.01,100000000.00]
            'body'           => $body,                      // 必填，商品详情
            'it_b_pay'       => '1d',                       // 可选，未付款交易的超时时间
            'notify_url'     => $notify_url,                // 可选，服务器异步通知页面路径
            'passback_params'=>'Apay'
        );
        //生成需要签名的订单
        $orderInfo = createLinkstring($parameter);
        //签名
        $sign = rsaSign($orderInfo);
        //生成订单
        return $orderInfo.'&sign="'.$sign.'"&sign_type="RSA"';
    }


    public function wechat_create(Request $request)
    {
        $order_find = Order::where('order_sn',$request->get('order_sn','O1499162589'))->first();
        $options = $this->options();
        $app = new Application($options);
        $payment = $app->payment;
        $out_trade_no = $order_find->order_sn; //拼一下订单号
        $attributes = [
            'trade_type'       => 'APP', // JSAPI，NATIVE，APP...
            'body'             => 'E住商购物',
            'detail'           => 'E住商购物', //我这里是通过订单找到商品详情，你也可以自定义
            'out_trade_no'     => $out_trade_no,
            'total_fee'        => (($order_find->sum_price)+($order_find->freight)-($order_find->use_integral))*100,
            'notify_url'       =>'http://egui.gebixianxiang.com/wechat/notify'
        ];
        $order = new \EasyWeChat\Payment\Order($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $order_find->pay_type = 2; //在这里更新订单的支付ID
            $order_find->save();
            // return response()->json(['result'=>$result]);
            $prepayId = $result->prepay_id;
            $config = $payment->configForAppPayment($prepayId);
            return response()->json($config);
        }
    }
}
